#include "CServer.h"

CServer::CServer(QObject* parent)
    : QObject(parent)
{    
    Port = 8000; //default port

    m_bServerstarted = false;
}

CServer::~CServer()
{
    if(m_bServerstarted == false)
            return;

    delete m_pZoidServ;
    delete m_pZoidCommunicator;
}


void CServer::SetCallbackGUI(QObject* CallbackGUI)
{
    m_pConfigDialog = CallbackGUI;
    QObject::connect(this,SIGNAL(emit_UpdateServerLog(QString)),m_pConfigDialog,SLOT(receive_UpdateServerLog(QString)));
}

void CServer::StartServer(int port)
{
    if(m_bServerstarted)
    {
        this->emitLogMessages("Server already started");
        return;
    }

    // initialize Zoidcom - write all output to zoidcom.log
    m_pZoidCommunicator = new ZoidCom("./logs/zoidcom.log");
    if (!m_pZoidCommunicator || !m_pZoidCommunicator->Init())
    {
        this->emitLogMessages("Failed to initialize server communication object");
        return;
    }

    // create instance of our Server class
    m_pZoidServ = new CZoidServer(this);
    m_pZoidServ->ZCom_setDebugName("d-t-p-Server");

    if (!m_pZoidServ->ZCom_initSockets(true /* use udp */, port /* udp port */, 0 /* no internal socket */))
    {
        this->emitLogMessages("Failed to initialize sockets");
        return;
    }

    m_bServerstarted = true;

    // Tell the GUI the server was started. This code is nested here because I have still to learn
    // about multithreading and the messagequeue in QT. I will try to emit a signal for the correct
    // GUI slot to catch and update the gui
    this->emitLogMessages("Server running");

    // register all zoidcom classes - this is needed for zoidcom. It depends on the fact that every
    // class that will be used over networks is registered as shown in the function below
    RegisterClassesForZoidOP();

    // create and register lobby radio. The registration happens by itself
    m_pLobbyRadio = new CZoidLobbyRadio(m_pZoidServ);

    while ( m_bServerstarted )
    {
        // continually run server
        // tell the server to process incoming data
        m_pZoidServ->ZCom_processInput();
        // tell the server to process outgoing data
        m_pZoidServ->ZCom_processOutput();
        // give up remaining cpu time
        m_pZoidCommunicator->Sleep(1);
    }

    this->emitLogMessages("Server stopped");
    return;
}

void CServer::emitLogMessages(QString message)
{
    emit_UpdateServerLog(message);
}

void CServer::start()
{
    this->StartServer(Port);
}

void CServer::RegisterClassesForZoidOP()
{
    CZoidLobbyRadio::registerClass(m_pZoidServ);
}

